package code.example.base.nio;

import code.example.tool.LogFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class TestServerSocketChannel {

    public void start(){
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            Selector selector = Selector.open();
            serverSocketChannel.bind(new InetSocketAddress(8080));
            serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT,null);

            while(selector.select() >0){
                Set<SelectionKey> selectionKeys =  selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while(iterator.hasNext()){
                    SelectionKey  selectionKey=  iterator.next();
                    if(selectionKey.isValid()){
                        SelectableChannel selectableChannel = selectionKey.channel();
                        if(selectionKey.isAcceptable()){

                            ServerSocketChannel serverSocketChannel1 = (ServerSocketChannel)selectableChannel;
                            SocketChannel socketChannel = serverSocketChannel1.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector,SelectionKey.OP_READ);
                            LogFactory.getLog().info("accept happen  for:"+socketChannel.getRemoteAddress());
                        }else if(selectionKey.isReadable()){
                            if(SocketChannel.class.isInstance(selectableChannel)){
                                SocketChannel socketChannel = (SocketChannel)selectableChannel;
                                ByteBuffer byteBuffer =ByteBuffer.allocate(1024);
                                int size = socketChannel.read(byteBuffer);
                                String str = new String(byteBuffer.array());
                                LogFactory.getLog().info("read from remote:"+str);
                                selectionKey.cancel();
                                socketChannel.close();
                            }
                        }
                    }
                    iterator.remove();
                }
            }
        }catch(IOException e){
            LogFactory.getLog().error(e);
        }

    }
    public static void main(String [] args){
        new TestServerSocketChannel().start();
    }
}
